# -*- coding: utf-8 -*-
# created on 2016/8/24

from mathsolver.functions.base import *
from sympy import sqrt, Rational, solveset


class ShuYuShiMiniSqrtTongLei(BaseFunction):
    """
    ShuYuShiMiniSqrtTongLei().solver(BasePoly("sqrt(x**2-4*x)"), BasePoly("3*sqrt(10-x)"))
    ShuYuShiMiniSqrtTongLei().solver(BasePoly("sqrt(3*a-8)"), BasePoly("sqrt(17-2*a)"))
    """
    def get_pingfanggen(self, expr):
        if expr.is_Pow and expr.args[1] == Rational(1, 2):     # 当表达式是一个二次根式形式时，直接返回平方根
            return expr.args[0]
        elif expr.is_Mul:       # 当表达式是由乘号连接时，进一步判断每一乘项是否为根式
            for item in expr.args:
                expr_result = self.get_pingfanggen(item)
                if expr_result is not None:
                    return expr_result
            return None     # 如果表达式中每一根式，返回None
        else:
            return None

    def solver(self, *args):
        expr1, expr2 = args[0].sympify(), args[1].sympify()
        assert not expr1.is_Add and not expr2.is_Add
        expr1_genshi, expr2_genshi = self.get_pingfanggen(expr1), self.get_pingfanggen(expr2)     # 获取表达式的平方根
        self.steps.append(['由题意得:', '%s=%s' % (new_latex(expr1), new_latex(expr2))])
        if expr1_genshi is not None and expr2_genshi is not None:
            expr = expr1_genshi - expr2_genshi
            symbol = expr.free_symbols.pop()
            result = solveset(Eq(expr, 0), symbol)
            self.steps.append(['解得：', BaseSymbolValue({symbol: result}).printing()])
            # 判断结果是否都满足最简二次根式的定义
            for item in result:
                if sqrt(expr1_genshi.replace(expr.free_symbols.pop(), item)).is_Mul \
                        or sqrt(expr2_genshi.replace(expr.free_symbols.pop(), item)).is_Mul:
                    result = FiniteSet(item).complement(result)
                    self.steps.append(['当%s=%s' % (new_latex(expr.free_symbols.pop()), new_latex(item)), '是不满足为最简二次根式，故舍去'])
            self.output.append(BaseSymbolValue({symbol: result}))
        else:
            raise ValueError("unexpected situation")
        return self


if __name__ == '__main__':
    pass
